package com.sky.mapper;

import com.github.pagehelper.Page;
import com.sky.annotation.AutoFill;
import com.sky.dto.DishInventoryPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishInventory;
import com.sky.entity.OrderDetail;
import com.sky.enumeration.OperationType;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Mapper
public interface DishInventoryMapper {

    /**
     * 插入库存信息
     */
    @AutoFill(value = OperationType.INSERT)
    @Insert("insert into dish_inventory (dish_id,dish_name,create_time,update_time) " +
            "values (#{id},#{name},#{createTime},#{updateTime})")
    void add(Dish dish);

    /**
     * 分页查询库存信息
     * @param dishInventoryPageQueryDTO
     * @return
     */
    Page<DishInventory> pageQuery(DishInventoryPageQueryDTO dishInventoryPageQueryDTO);

    /**
     * 修改库存信息
     * @param dishInventory
     */
    void update(DishInventory dishInventory);

    /**
     * 批量删除库存信息
     * @param dishIds
     */
    void delete(List<Long> dishIds);

    /**
     * 根据菜品id查询库存量
     *
     * @param dish
     * @return
     */
    @Select("select stock from dish_inventory where dish_id=#{dishId}")
    Integer selectByDishId(OrderDetail dish);

    /**
     * 扣减库存（原子性）
     * @param dishId
     * @param requiredNum
     * @return
     */
    @Update("""
    UPDATE dish_inventory 
    SET stock = stock - #{requiredNum} 
    WHERE dish_id = #{dishId} 
      AND stock >= #{requiredNum}
""")
    int reduceStock(@Param("dishId") Long dishId,@Param("requiredNum") Integer requiredNum);

    /**
     * 获取库存
     * @param key
     * @return
     */
    @Select("select stock from dish_inventory where dish_id=#{key}")
    int getStock(Long key);
}
